//
//  IATViewController.h
//  MSCDemo_UI
//
//  Created by wangdan on 15-4-28.
//
//

#import "IATViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "TAMacro.h"
#import "PopupView.h"
#import "ISRDataHelper.h"
#import "IATConfig.h"

@interface IATViewController ()
@property (nonatomic, copy) NSString *returnResultString;
@end

@implementation IATViewController


#pragma mark - 视图生命周期


-(void)viewDidLoad
{
   
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height * 0.4)];
    [self.view addSubview:_textView];
    self.textView.backgroundColor = [UIColor grayColor];
    self.textView.font = [UIFont fontWithName:@"Helvetica" size:21];
    self.textView.textColor = [UIColor whiteColor];
    
    self.textView.text = @"可无视语音识别后自动添加的标点符号,点击确认按钮返回后,如无数据,则说明该商品不存在!";
    
    self.startRecBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startRecBtn.frame = CGRectMake(0, self.view.bounds.size.height *0.45 + 64, self.view.bounds.size.width / 3 , self.view.bounds.size.height * 0.1);
   // [self.startRecBtn setTitle:@"开始讲话" forState:UIControlStateNormal];
    [self.view addSubview:self.startRecBtn];
    [self.startRecBtn setImage:[UIImage imageNamed:@"huatonghui"] forState:UIControlStateNormal];
     [self.startRecBtn addTarget:self action:@selector(startBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.stopRecBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.stopRecBtn.frame = CGRectMake(self.view.bounds.size.width / 3, self.view.bounds.size.height *0.45 +64, self.view.bounds.size.width / 3 , self.view.bounds.size.height * 0.1);
 
    [self.view addSubview:self.stopRecBtn];
    [self.stopRecBtn addTarget:self action:@selector(stopBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.stopRecBtn setImage:[UIImage imageNamed:@"结束灰"] forState:UIControlStateNormal];
    
    self.cancelRecBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelRecBtn.frame = CGRectMake(self.view.bounds.size.width / 3 * 2, self.view.bounds.size.height *0.45 + 64, self.view.bounds.size.width / 3 , self.view.bounds.size.height * 0.1);
    
    [self.view addSubview:self.cancelRecBtn];
    [self.cancelRecBtn addTarget:self action:@selector(cancelBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelRecBtn setImage:[UIImage imageNamed:@"quxiaohui"] forState:UIControlStateNormal];
    self.Backbutton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.bounds.size.width * 0.4, self.view.bounds.size.height * 0.7,self.view.bounds.size.width * 0.2, self.view.bounds.size.width * 0.2 )];
    
   
    [self.Backbutton addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: self.Backbutton];
    [self.Backbutton setImage:[UIImage imageNamed:@"wanchenghui"] forState:UIControlStateNormal];
    
    
    
    [self.startRecBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.stopRecBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.cancelRecBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    
    [super viewDidLoad];
    
    _textView.layer.borderWidth = 0.5f;
    _textView.layer.borderColor = [[UIColor whiteColor] CGColor];
    [_textView.layer setCornerRadius:7.0f];
    
    CGFloat posY = self.textView.frame.origin.y+self.textView.frame.size.height/6;
    _popUpView = [[PopupView alloc] initWithFrame:CGRectMake(100, posY, 0, 0) withParentView:self.view];

    self.uploader = [[IFlyDataUploader alloc] init];

    //demo录音文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    _pcmFilePath = [[NSString alloc] initWithFormat:@"%@",[cachePath stringByAppendingPathComponent:@"asr.pcm"]];
    
}


-(void)viewWillAppear:(BOOL)animated
{
   
    
    [super viewWillAppear:animated];
    
    [self initRecognizer];//初始化识别对象
    
    [_startRecBtn setEnabled:YES];
    
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil];
    
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.title = @"语音识别";
   
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.view = nil;
}

-(void)viewWillDisappear:(BOOL)animated
{
   
    
    if ([IATConfig sharedInstance].haveView == NO) {//无界面
        [_iFlySpeechRecognizer cancel]; //取消识别
        [_iFlySpeechRecognizer setDelegate:nil];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    else
    {
        [_iflyRecognizerView cancel]; //取消识别
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    
    
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}


-(void)dealloc
{
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - 按钮响应函数

/**
 启动听写
 *****/
- (void)startBtnHandler:(id)sender {
    
    NSString * vol = @"我在听! , 请您开说说话";
    [_popUpView showText: vol];
    
    if ([IATConfig sharedInstance].haveView == NO) {//无界面
        
        [_textView setText:@""];
        [_textView resignFirstResponder];
        self.isCanceled = NO;
        
        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }
        
        [_iFlySpeechRecognizer cancel];
        
        //设置音频来源为麦克风
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置听写结果格式为json
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //保存录音文件，保存在sdk工作路径中，如未设置工作路径，则默认保存在library/cache下
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {

        }else{
            [_popUpView showText: @"启动识别服务失败，请稍后重试"];//可能是上次请求未结束，暂不支持多路并发
        }
    }
}

/**
 停止录音
 *****/
- (void)stopBtnHandler:(id)sender {
    
    [_iFlySpeechRecognizer stopListening];
    [_textView resignFirstResponder];
}

/**
 取消听写
 *****/
- (void)cancelBtnHandler:(id)sender {
    self.isCanceled = YES;
    
    [_iFlySpeechRecognizer cancel];
    
    NSString * vol = @"放弃录入!";
    [_popUpView showText: vol];
    
    [_textView resignFirstResponder];
}

#pragma mark - IFlySpeechRecognizerDelegate

/**
 音量回调函数
 volume 0－30
 ****/
- (void) onVolumeChanged: (int)volume
{
    if (self.isCanceled) {
        [_popUpView removeFromSuperview];
        return;
    }
    
   NSString * vol = [NSString stringWithFormat:@"音量：%d",volume];
    [_popUpView showText: vol];
}



/**
 开始识别回调
 ****/
- (void) onBeginOfSpeech
{
   
    [_popUpView showText: @"正在录音"];
}

/**
 停止录音回调
 ****/
- (void) onEndOfSpeech
{
 
    
    [_popUpView showText: @"停止录音"];
}


/**
 听写结束回调（注：无论听写是否正确都会回调）
 error.errorCode =
 0     听写正确
 other 听写出错
 ****/
- (void) onError:(IFlySpeechError *) error
{
   
    if ([IATConfig sharedInstance].haveView == NO ) {
        NSString *text ;
        
        if (self.isCanceled) {
            text = @"识别取消";
            
        } else if (error.errorCode == 0 ) {
            if (_result.length == 0) {
                text = @"无识别结果";
            }else {
                text = @"识别成功";
            }
        }else {
            text = [NSString stringWithFormat:@"发生错误：%d %@", error.errorCode,error.errorDesc];
            
        }
        
        [_popUpView showText: text];

        
        
        
    }else {
        [_popUpView showText:@"识别结束"];
       // NSLog(@"errorCode:%d",[error errorCode]);
    }
    
    [_startRecBtn setEnabled:YES];
  
}

/**
 无界面，听写结果回调
 results：听写结果
 isLast：表示最后一次
 ****/
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
  
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    _result =[NSString stringWithFormat:@"%@%@", _textView.text,resultString];
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    
    
    
    _textView.text = [NSString stringWithFormat:@"%@%@", _textView.text,resultFromJson];
    
    NSLog(@"%@",_textView.text);
    
    
    if (isLast){
        NSLog(@"听写结果(json)：%@测试",  self.result);
    }
         //返回结果
    

    
    self.returnResultString = _textView.text;
    
    
}


//返回方法

- (void)returnBack{

   
    
    
    if (self.returnResultString.length > 0 ) {
       
        self.ReturnVoiceString(self.returnResultString);

         [self.navigationController popViewControllerAnimated:YES];
        
    }
   
    
    
}



/**
 听写取消回调
 ****/
- (void) onCancel
{
    NSLog(@"识别取消");
}

/**
 设置识别参数
 ****/
-(void)initRecognizer
{
   
    
    if ([IATConfig sharedInstance].haveView == NO) {//无界面
        
        //单例模式，无UI的实例
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
            
            [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
            
            //设置听写模式
            [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        }
        _iFlySpeechRecognizer.delegate = self;
        
        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            
            //设置最长录音时间
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置后端点
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //设置前端点
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //网络等待时间
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //设置采样率，推荐使用16K
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            if ([instance.language isEqualToString:[IATConfig chinese]]) {
                //设置语言
                [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
                //设置方言
                [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            }else if ([instance.language isEqualToString:[IATConfig english]]) {
                [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            }
            //设置是否返回标点符号
           
             [_iflyRecognizerView setParameter:[IATConfig noDot] forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
        }
}


@end
